//
//  SceneDelegate.swift
//  SwiftUIDemo
//
//  Created by Kael on 2019/11/3.
//  Copyright © 2019 Kael. All rights reserved.
//

import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    
    func getImageFromGroup(imagePath:URL?) -> UIImage? {
        let imagePath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.widget.swiftui.demo")
//        let imageData = try! Data(contentsOf: imagePath)
        
        return UIImage(contentsOfFile: imagePath?.absoluteString ?? "")
//        return UIImage(data: imageData)
    }

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
//        let contentView = ContentView()
//        let contentView = LandMarkList()
//        let contentView = LXCalendarView()
// 共享基本数据类型
        
        let groupID = "group.widget.swiftui.demo"
        
        let userData = UserDefaults(suiteName: groupID)
        
        userData?.set(2, forKey: "userdata")
        
        userData?.set("group name", forKey: "groupName")
        
        //  共享自定义Model
        let groupFileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupID)

        let backImage = UIImage(named: "screen")

        let imageData:Data = backImage!.pngData()!
        
        try? imageData.write(to: URL(fileURLWithPath: groupFileURL?.absoluteString ?? "" + "/screen.png"))
        
    
//        UserDefaults(suiteName: "group.widget.swiftui.demo")?.set("group name", forKey: "groupName")
        
        // 然后在后面保存数据
        let contentView = LXLiveRootView()

        if (getImageFromGroup(imagePath: URL(fileURLWithPath: groupFileURL?.absoluteString ?? "" + "/screen.png")) != nil) {
            print("有")
        }else{
            print("NO presented")
        }
        
        if ((groupFileURL?.absoluteString) != nil) {
            print("\(String(describing: groupFileURL?.absoluteString))")
        }
        
        
        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
        
        getJoke()
    }
    
    func getJoke() {

//            let url = URL(string: "https://zkapisdev.lexue.com/study/course/live/get/live/schedule")!
//            var urlRequest = URLRequest(url:url)
//            urlRequest.addValue("text/plain",forHTTPHeaderField: "Accept")
        
        
        

        let jsonstr="{\"status\":\"1\",\"data\":{\"udid\":\"5bce8b974adbc6a60858d41657f1761305f62ce9\",\"time\":\"1580546728\",\"orderid\":\"20200201164519672\"}}"
        let jsondata = jsonstr.data(using: .utf8)


        do {
            let ok =  try JSONSerialization.jsonObject(with: jsondata!, options: .mutableContainers) as AnyObject
            
            let status:String=ok["status"] as! String
            
            if(status=="1"){
            
                let jsonObject:AnyObject?=ok["data"] as! AnyObject
                if let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: []){
                    
                    let newStr = String(data: jsonData, encoding: String.Encoding.utf8)
                    
                    let ok =  try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as AnyObject
                    
                    print(ok["udid"] as! String)
                    
                }
                
            }
            
        } catch {
            print(error)
        }

            

    }
    
    

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}


struct SceneDelegate_Previews: PreviewProvider {
    static var previews: some View {
        /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
    }
}
